<template>
  <el-tree-select
    :data="clientTreeData"
    :props="props"
    filterable
    multiple
    show-checkbox
    check-strictly
    node-key="id"
    @check-change="handleCheckChange"
    v-model="selectedValue"
    style="min-width: 200px"
  >
  <template #default="{ node, data }">
    <div class="custom-tree-node">
      <el-icon
          class="el-tree-node__expand-icon"
          @click="handleExpandIconClick(node, data, $event)"
      >
        <component :is="node.expanded ? 'arrow-down' : 'arrow-right'"></component>
      </el-icon>
      <span class="node-label">{{ data.name }}</span>
    </div>
  </template>
  </el-tree-select>
</template>

<script>
import request from "@/utils/request.js";

export default {
  name: "ClientTree",
  props: {
    selected: {
      type: Array
    },
    props: {
      type: Object,
      default: () => ({
        children: "children",
        label: "name",
        id: "id",
      }),
    },
  },
  data() {
    return {
      clientTreeData: [],
      selectedValue: ''
    };
  },
  created() {
    this.getFirstClient();
    console.log(this.selected)
  },
  methods: {
    // 展开节点
    async handleExpandIconClick(node, data, event) {
      await this.getNodeChildren(data)
      event.stopPropagation();
      node.expanded = !node.expanded;

      // 如果当前节点被选中/禁用，禁用其子节点
      if (data.disabled || node.checked) {
        // 获取子节点
        console.log("展开获取子节点")
        let childNodes = this.getChildNodes(data);
        console.log(childNodes)
        childNodes.forEach(node => {
          node.disabled = true
        })
      }
    },
    handleCheckChange(data, checked) {
      console.log("选中数据：", data);
      // 获取选中节点的相关父节点和子节点
      if (checked) {
        console.log("选中")
        // 如果当前节点被选中，获取父节点和子节点
        this.getNodeRelations(data,true);
        // 将父节点和子节点  disabled=true
      }else {
        console.log("取消选中")
        this.getNodeRelations(data,false);
      }
    },
    // 获取选中节点的相关父节点（祖先节点）
    getNodeRelations(data,disabled) {
      let parentNodes = this.getParentNodes(this.clientTreeData, data);
      let childNodes = this.getChildNodes(data);

      console.log("父节点及祖先节点：", parentNodes);
      console.log("子节点及子节点的子节点：", childNodes);

      // 禁用除当前节点外的父节点和子节点
      parentNodes.forEach(node => {
        if (disabled){
          if (node.id!==data.id){
            node.disabled = disabled;
          }
        }else {
          node.disabled = disabled;
        }
      })
      childNodes.forEach(node => {
        node.disabled=disabled
      })
    },

    // 递归获取父节点及祖先节点
    getParentNodes(nodes, targetNode) {
      let parents = [];

      // 遍历当前节点的子节点
      for (let node of nodes) {
        // 如果当前节点是目标节点，直接返回父节点链
        if (node.id === targetNode.id) {
          parents.push(node)
          return parents;
        }

        // 如果当前节点有子节点，递归查找
        if (node.children && node.children.length) {
          let result = this.getParentNodes(node.children, targetNode);
          if (result.length > 0) {
            parents.push(node); // 当前节点是目标节点的父节点
            parents = parents.concat(result); // 添加父节点的祖先节点
            return parents; // 一旦找到目标节点的父节点链，立即返回
          }
        }
      }

      return parents;
    },
    // 递归获取子节点及子节点的子节点
    getChildNodes(node) {
      console.log(node)
      let children = [];
      if (node.children && node.children.length) {
        for (let child of node.children) {
          children.push(child);
          children = children.concat(this.getChildNodes(child)); // 深度搜索
        }
      }
      return children;
    },
    async getNodeChildren(data) {
      if (data.children && data.children.length > 0) {
        return;
      }
      try {
        const res = await request.get(`/client/findChildClient?pcId=${data.id}`);
        if (res.data.total > 0) {
          data.children = res.data.record;
        }
      } catch (error) {
        this.$message.error("获取单位子节点数据失败：" + error);
      }
    },
    async getFirstClient() {
      try {
        let level = JSON.parse(localStorage.getItem("user")).level
        let organizationId = JSON.parse(localStorage.getItem("user")).organization
        let isAllClient = JSON.parse(localStorage.getItem("user")).isAllClient;
        let userId = JSON.parse(localStorage.getItem("user")).id;
        await request.get("/client/getSubordClient?level=" +
            level + "&organizationId=" + organizationId + "&isAllClient=" + isAllClient + "&userId=" + userId).then(res => {
          if (res.data.total > 0) {
            this.clientTreeData = res.data.record;
          } else {
            this.$message.error("无数据")
          }
        })
      } catch (error) {
        this.$message.info("获取一级单位失败" + error)
      }
    },
  }
};
</script>

<style scoped>
.custom-tree-node {
  display: flex;
  align-items: center;
}

.node-label {
  flex-grow: 1;
  margin-left: 8px;
}

.el-tree-node__expand-icon {
  margin-left: 0;
  margin-right: 5px;
  cursor: pointer;
}
</style>
